package com.hopedove.yieldmanage.activity;

import static org.koin.java.KoinJavaComponent.inject;

import android.app.Activity;
import android.app.DatePickerDialog;
import android.app.DatePickerDialog.OnDateSetListener;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.hopedove.base.BaseActivity;
import com.hopedove.data.Datetime;
import com.hopedove.net.ErrResponse;
import com.hopedove.net.OkResponse;
import com.hopedove.net.domain.Communication;
import com.hopedove.repository.CommonRepository;
import com.hopedove.utils.DateTimeUtil;
import com.hopedove.utils.ParseUtils;
import com.hopedove.utils.ToastUtil;
import com.hopedove.view.SimpleDialog;
import com.hopedove.view.SimpleInputDialog;
import com.hopedove.yieldmanage.R;
import com.hopedove.yieldmanage.adapter.InputListAdapter;
import com.hopedove.yieldmanage.domain.net.DeleteYieldInput;
import com.hopedove.yieldmanage.domain.net.GetInputList;
import com.hopedove.yieldmanage.domain.net.GetYieldInput;
import com.hopedove.yieldmanage.domain.net.SaveYieldInput;
import com.hopedove.yieldmanage.domain.net.SelectDict;
import com.hopedove.yieldmanage.entity.ProductInputEntity;
import com.hopedove.yieldmanage.entity.SpinnerEntity;
import com.hopedove.yieldmanage.utils.ScanGun;
import com.hopedove.yieldmanage.utils.SharedPreUtil;

import org.json.JSONArray;
import org.json.JSONObject;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

import kotlin.Lazy;

public class YieldInputActivity extends BaseActivity implements OnClickListener {

    private Lazy<CommonRepository> commonRepo = inject(CommonRepository.class);
    /**
     * activity销毁时，存储product的key值
     **/
    private final static String PRODUCTLIST = "productList";
    /**
     * activity销毁时，存储三联单号的key值
     **/
    private final static String CLOTHTKTNO = "clothTktNo";
    /**
     * listview适配器
     **/
    private InputListAdapter mAdapter;
    /**
     * 当前产量列表
     **/
    private List<ProductInputEntity> mProductList = new ArrayList<>();
    private List<ProductInputEntity> mSaveProductList = new ArrayList<>();
    private List<ProductInputEntity> mDeleteProductList = new ArrayList<>();

    private ListView mListView;

    private LinearLayout mDateLl;

    private TextView mDateTv;
    private ImageView mClearImg;

    private Button mSearchBtn;

    private Button mDeleteBtn;

    private Button mSaveBtn;
    /**
     * 三联单号，扫描条码自动带出
     **/
    private EditText mClothTktNoEt;
    /**
     * 车号
     **/
    private EditText mMachineNoEt;

    private TextView mCountTv;

    /**
     * 记录三联单号
     **/
    private String mClothThtNo;
    /**
     * 存储下拉框文本
     **/
    private List<String> mSpList = new ArrayList<String>();
    /**
     * 扫描枪控制类
     **/
    private ScanGun mScanGun;
    /**
     * 存储日期
     **/
    private String mJobDate = "";

    /**
     * 员工工号
     **/
    private String mJobNum = "";
    /**
     * 员工登录的车间，text值
     **/
    private String mBmmc = "";
    private int mCount = 0;
    final private Activity self = this;

    private Datetime defaultDatetime;
    private SimpleInputDialog inputDialog;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.input_activity);
        getDefaultDate();
        initDate();
        initView();
        initEvent();
        if (savedInstanceState != null) {
            mProductList.clear();
            // toast("大小" + mProductList.size());
            mProductList.addAll((List<ProductInputEntity>) savedInstanceState.getSerializable(PRODUCTLIST));
            // toast("大小" + mProductList.size());
            mAdapter.notifyDataSetChanged();
            checkListView();
            mClothThtNo = savedInstanceState.getString(CLOTHTKTNO);
            mClothTktNoEt.setText(mClothThtNo);

        }
        startGetInputList();
    }

    private void initDate() {
        mJobDate = defaultDatetime.dateFormatEn();

        mSpList.add("请选择原因");
        mJobNum = (String) SharedPreUtil.getValue(this, SharedPreUtil.YHM, "");
        mBmmc = (String) SharedPreUtil.getValue(this, SharedPreUtil.BMMC, "");
    }

    private void initView() {
        mListView = findViewById(R.id.input_listView);
        mDateLl = findViewById(R.id.input_dateLl);
        mDateTv = findViewById(R.id.input_dateTv);
        mClothTktNoEt = findViewById(R.id.input_clothTktNoEt);
        mMachineNoEt = findViewById(R.id.input_machineNoEt);
        mClearImg = findViewById(R.id.input_clearImg);
        mSearchBtn = findViewById(R.id.input_searchBtn);

        mDeleteBtn = findViewById(R.id.input_deleteBtn);

        mSaveBtn = findViewById(R.id.input_saveBtn);
        mCountTv = findViewById(R.id.input_countTv);

        mAdapter = new InputListAdapter(this, mProductList, mJobDate);
        // 这一步很关键，不要忘了，使得adapter支持局部刷新
        mAdapter.setListView(mListView);
        //mDateTv.setText(dateFormat_ZH.format(Calendar.getInstance().getTime()));
        mDateTv.setText(defaultDatetime.dateFormatCn());

        // 设置分割线
        mListView.setDivider(getDrawableCompat(R.color.line));
        // 设置分割线高度
        mListView.setDividerHeight(1);
        mListView.setAdapter(mAdapter);
        // 获取原因列表
        selectDict();

        mClothTktNoEt.setFocusable(true);
        mClothTktNoEt.setFocusableInTouchMode(true);

        mClothTktNoEt.requestFocus();
        mClothTktNoEt.requestFocusFromTouch();
        mClothTktNoEt.findFocus();

        mAdapter.setOnEditTextClickListener(new OnEditTextClickImpl());
    }

    private class OnEditTextClickImpl implements InputListAdapter.OnEditTextClickListener {
        private long lastClickTime;

        @Override
        public void onClick(Bundle extras) {
            if (!isFastClick()) {
                if (inputDialog == null) {
                    inputDialog = new SimpleInputDialog((value, bundle) -> {
                        mAdapter.updateEditText(bundle, value);
                    });
                }

                if (inputDialog.isShowing()) {
                    inputDialog.dismissAllowingStateLoss();
                }
                inputDialog.show(YieldInputActivity.this, extras);
            }
        }

        private boolean isFastClick() {
            long current = System.currentTimeMillis();
            long old = lastClickTime;
            lastClickTime = current;
            return current - old < 500;
        }

    }

    /**
     * 初始化事件
     */
    private void initEvent() {

        mDateLl.setOnClickListener(this);
        mClearImg.setOnClickListener(this);
        mDeleteBtn.setOnClickListener(this);
        mSearchBtn.setOnClickListener(this);
        mSaveBtn.setOnClickListener(this);

        mClothTktNoEt.setOnKeyListener((v, keyCode, event) -> {
            if (event != null && event.getKeyCode() == KeyEvent.KEYCODE_ENTER && event.getAction() == KeyEvent.ACTION_UP) {
                startGetInput();
                return true;
            }
            return false;
        });


        mClothTktNoEt.setOnTouchListener((v, event) -> {
            // 清空listview的焦点位置，不然弹出键盘焦点不在这
            mAdapter.setFocusIndex(-1);
            return false;
        });


        mAdapter.setOnCheckClickListener((position, isChecked) -> {
            mProductList.get(position).isChecked = isChecked;
            mCount = 0;
            for (int i = 0; i < mProductList.size(); i++) {
                if (mProductList.get(i).isChecked) {
                    mCount++;
                }
            }
            mCountTv.setText("已选择\n" + mCount + "项");
        });

    }

    @Override
    public void onClick(View v) {
        final int id = v.getId();
        if (id == R.id.input_dateLl) {
            setDate();
        } else if (id == R.id.input_clearImg) {
            mClothTktNoEt.setText("");
        } else if (id == R.id.input_searchBtn) {
            startGetInputList();
        } else if (id == R.id.input_saveBtn) {
            startSaveInputList();
        } else if (id == R.id.input_deleteBtn) {
            startDeleteInputList();
        }
    }

    /**
     * 准备查询已录入的数据，根据日期和车号
     */
    private void startGetInputList() {
        String machineNo = mMachineNoEt.getText().toString().trim();

        getInputList(machineNo);
    }

    /**
     * 准备查询数据 根据三联单号
     */
    private void startGetInput() {
        String clothTktNo = mClothTktNoEt.getText().toString().trim();
        String jobNum = (String) SharedPreUtil.getValue(this, SharedPreUtil.YHM, "");
        if (TextUtils.isEmpty(clothTktNo)) {
            SimpleDialog.show(self, "三联单号不能为空!");
            return;
        }
        for (ProductInputEntity product : mProductList) {
            if (clothTktNo.equals(product.MACHINENO + product.CLOTHTKTNO)) {
                SimpleDialog.show(self, "该三联单号已存在,请不要重复录入!");
                mClothTktNoEt.setText("");
                return;
            }
        }
        getInput(clothTktNo, jobNum);
    }

    /**
     * 保存录入的产量
     */
    private void startSaveInputList() {

        // 每次保存之前都要进行清空，可能存在上一次保存失败的情况下，数据还存在list中
        mSaveProductList.clear();
        for (int i = 0; i < mProductList.size(); i++) {
            if (mProductList.get(i).isChecked) {
                // 添加到需要保存的列表中
                mSaveProductList.add(mProductList.get(i));

            }
        }
        if (mProductList.size() == 0) {
            SimpleDialog.show(this, "当前列表为空，请添加数据！");
            stopWait();
            return;
        }

        if (mSaveProductList.size() == 0) {
            SimpleDialog.show(this, "请勾选需要保存的数据！");
            stopWait();
            return;
        }
        for (ProductInputEntity product : mSaveProductList) {
            if (TextUtils.isEmpty(product.MACHINE_SPEED)) {
                SimpleDialog.show(this, "车速不能为空！");
                stopWait();
                return;
            }
            if (TextUtils.isEmpty(product.ROTATION_RATE)) {
                SimpleDialog.show(this, "转速不能为空！");
                stopWait();
                return;
            }

            if (TextUtils.isEmpty(product.ONDUTY_FRAMES) && TextUtils.isEmpty(product.CHANGE_FRAMES) && TextUtils.isEmpty(product.TAKEDUTY_FRAMES)) {
                SimpleDialog.show(this, "格数不能为空！");
                stopWait();
                return;
            }
            if ("0".equals(product.REQUIREWEIGHT) || "0.0".equals(product.REQUIREWEIGHT)) {
                SimpleDialog.show(this, "要求重量不能为0，请重新录入正确的格数！");
                stopWait();
                return;
            }

            if (TextUtils.isEmpty(product.CLASSES)) {
                SimpleDialog.show(this, "请选择班次！");
                stopWait();
                return;
            }
        }
        saveInputList();
    }

    /**
     * 准备进行删除操作
     */
    private void startDeleteInputList() {
        List<String> PKIDList = new ArrayList<String>();

        for (int i = 0; i < mProductList.size(); i++) {
            if (mProductList.get(i).isChecked) {
                mDeleteProductList.add(mProductList.get(i));

                // 添加到需要保存的列表中
                if (!TextUtils.isEmpty(mProductList.get(i).PKID)) {
                    PKIDList.add(mProductList.get(i).PKID);
                }

            }
        }
        if (mDeleteProductList.size() == 0) {
            SimpleDialog.show(this, "请勾选需要删除的数据！");
            stopWait();
            return;
        }
        if (mProductList.size() == 0) {
            SimpleDialog.show(this, "当前列表为空，请添加数据！");
            stopWait();
            return;
        }

        deleteInputProduct(PKIDList);
    }

    /**
     * 获取下拉框列表的值
     */
    private void selectDict() {
        showWait();

        SelectDict selectDict = SelectDict.newOtherReasons();
        Communication.asyncRequest(selectDict, r -> {
            stopWait();
            if (r instanceof OkResponse) {
                try {
                    Gson gson = new Gson();
                    List<SpinnerEntity> spinnerEntityList = gson.fromJson(((OkResponse) r).getData(), new TypeToken<List<SpinnerEntity>>() {
                    }.getType());
                    for (SpinnerEntity spinnerEntity : spinnerEntityList) {
                        mSpList.add(spinnerEntity.fieldValue);
                    }
                    mAdapter.setSpList(mSpList);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            } else if (r instanceof ErrResponse) {
                ToastUtil.longToast(self, ((ErrResponse) r).getErrText());
            }
        });
    }

    /**
     * 根据三联单号查询数据
     */
    private void getInput(String clothTktNo, String jobNum) {
        showWait();

        GetYieldInput getYieldInput = new GetYieldInput(clothTktNo, jobNum, mJobDate);
        Communication.asyncRequest(getYieldInput, r -> {
            stopWait();
            if (r instanceof OkResponse) {
                try {
                    String msg = "";
                    String opt = "";

                    JSONObject jsonObj = new JSONObject(((OkResponse) r).getData());
                    msg = jsonObj.optString("MSG_INFO");
                    opt = jsonObj.optString("OPT_FLAG");
                    if ("0".equals(opt)) {
                        ProductInputEntity product = new ProductInputEntity();
                        product = ParseUtils.parse(((OkResponse) r).getData(), ProductInputEntity.class);
                        // 设置员工工号
                        product.JOB_NUM = mJobNum;
                        // 设置日期
                        product.JOBDATE = mJobDate;
                        // 设置默认勾选
                        product.isChecked = true;

                        /********************************2017年12月2日 修改 ****************************/
                        /************新增时如果列表有相同车号的记录，则复制该车号的“车速、转速、班次”到新的记录中***********/

                        for (ProductInputEntity savedProduct : mProductList) {
                            if (product.MACHINENO.equals(savedProduct.MACHINENO)) {
                                product.MACHINE_SPEED = savedProduct.MACHINE_SPEED;
                                product.ROTATION_RATE = savedProduct.ROTATION_RATE;
                                product.CLASSES = savedProduct.CLASSES;
                                break;
                            }
                        }
                        /***********************************结束************************************/
                        // 每次在第一行增加数据
                        mProductList.add(0, product);
                        mAdapter.notifyDataSetChanged();
                        checkListView();
                        // 查询成功后，清空输入框
                        mClothTktNoEt.setText("");
                    } else if ("1".equals(opt)) {
                        SimpleDialog.show(this, msg);
                    } else if ("2".equals(opt)) {
                        SimpleDialog.show(this, msg);
                    } else if ("3".equals(opt)) {
                        SimpleDialog.show(this, msg);
                    } else if ("4".equals(opt)) {
                        SimpleDialog.show(this, msg);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }

    /**
     * 保存
     */
    private void saveInputList() {
        showWait();
        String userBean = (String) SharedPreUtil.getValue(this, SharedPreUtil.USERBEAN, "");

        SaveYieldInput saveYieldInput = new SaveYieldInput(userBean, mSaveProductList, mBmmc);
        Communication.asyncRequest(saveYieldInput, r -> {
            stopWait();
            if (r instanceof OkResponse) {
                try {
                    String msg = "";
                    String opt = "";
                    JSONObject jsonObj = new JSONObject(((OkResponse) r).getData());
                    msg = jsonObj.optString("MSG_INFO");
                    opt = jsonObj.optString("OPT_FLAG");
                    switch (opt) {
                        case "0":
                            SimpleDialog.show(this, "您已成功保存" + mSaveProductList.size() + "条数据！");
                            startGetInputList();
                            break;
                        case "1":
                        case "2":
                        case "3":
                            SimpleDialog.show(this, msg);
                            break;
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            } else if (r instanceof ErrResponse) {
                SimpleDialog.show(self, ((ErrResponse) r).getErrText());
            }
        });
    }

    /**
     * 查询该工号当前日期已经保存的数据
     */
    private void getInputList(String machineNo) {
        showWait();

        String userBean = (String) SharedPreUtil.getValue(this, SharedPreUtil.USERBEAN, "");
        GetInputList getInputList = new GetInputList(userBean, mJobNum, mJobDate, mBmmc, machineNo);
        Communication.asyncRequest(getInputList, r -> {
            stopWait();
            if (r instanceof OkResponse) {
                try {
                    String msg = "";
                    String opt = "";
                    JSONObject jsonObj = new JSONObject(((OkResponse) r).getData());
                    msg = jsonObj.optString("MSG_INFO");
                    opt = jsonObj.optString("OPT_FLAG");
                    switch (opt) {
                        case "0":
                            JSONArray resultArray = jsonObj.optJSONArray("result");
                            Gson gson = new Gson();
                            List<ProductInputEntity> productList = gson.fromJson(resultArray.toString(), new TypeToken<List<ProductInputEntity>>() {
                            }.getType());
                            mProductList.clear();
                            mProductList.addAll(productList);
                            mAdapter.notifyDataSetChanged();
                            checkListView();
                            break;
                        case "1":
                        case "2":
                        case "3":
                            SimpleDialog.show(this, msg);
                            break;
                    }
                } catch (Exception e) {
                    //ignore
                    ToastUtil.longToast(self, e.toString());
                }
            } else if (r instanceof ErrResponse) {
                SimpleDialog.show(self, ((ErrResponse) r).getErrText());
            }
        });
    }

    /**
     * 删除(工资产量录入)
     */
    private void deleteInputProduct(List<String> PKIDList) {
        showWait();
        String userBean = (String) SharedPreUtil.getValue(this, SharedPreUtil.USERBEAN, "");
        DeleteYieldInput deleteYieldInput = new DeleteYieldInput(userBean, PKIDList);
        Communication.asyncRequest(deleteYieldInput, r -> {
            stopWait();
            if (r instanceof OkResponse) {
                try {
                    String msg = "";
                    String opt = "";
                    JSONObject jsonObj = new JSONObject(((OkResponse) r).getData());
                    msg = jsonObj.optString("MSG_INFO");
                    opt = jsonObj.optString("OPT_FLAG");
                    switch (opt) {
                        case "0":
                            SimpleDialog.show(this, "您已成功删除" + mCount + "条数据！");
                            for (int i = 0; i < mDeleteProductList.size(); i++) {
                                for (int j = 0; j < mProductList.size(); j++) {
                                    if ((mProductList.get(j).MACHINENO + mProductList.get(j).CLOTHTKTNO).equals(mDeleteProductList.get(i).MACHINENO
                                            + mDeleteProductList.get(i).CLOTHTKTNO)) {
                                        mProductList.remove(j);
                                    }
                                }
                            }
                            mDeleteProductList.clear();
                            mAdapter.notifyDataSetChanged();
                            checkListView();
                            mCount = 0;
                            mCountTv.setText("已选择\n" + mCount + "项");
                            break;
                        case "1":
                        case "2":
                            SimpleDialog.show(this, msg);
                            break;
                    }
                } catch (Exception e) {
                    ToastUtil.longToast(self, e.toString());
                }
            } else if (r instanceof ErrResponse) {
                SimpleDialog.show(self, ((ErrResponse) r).getErrText());
            }
        });
    }

    /**
     * 检查 ListView 是否为空
     */
    private void checkListView() {
        if (mProductList.size() > 0) {
            mListView.setVisibility(View.VISIBLE);
        } else {
            mListView.setVisibility(View.GONE);
        }
    }

    private void getDefaultDate() {
        Datetime datetime = commonRepo.getValue().getServerDateTime(false);
        defaultDatetime = DateTimeUtil.adjustForSpecialShift(datetime);
    }

    /**
     * 设置日期
     */
    private void setDate() {
        // 获取当前年月日
        int year = defaultDatetime.year();
        int month = defaultDatetime.month();
        int day = defaultDatetime.dayOfMonth();

        DatePickerDialog datePickerDialog = new DatePickerDialog(this, mOnDateSetListener, year, month - 1, day);
        datePickerDialog.show();
    }

    /**
     * 日期选择监听器
     */
    OnDateSetListener mOnDateSetListener = new OnDateSetListener() {
        @Override
        public void onDateSet(DatePicker view, int year, int month, int dayOfMonth) {
            Datetime datetime = new Datetime(year, month + 1, dayOfMonth);
            mDateTv.setText(datetime.dateFormatCn());
            mJobDate = datetime.dateFormatEn();
            for (ProductInputEntity product : mProductList) {
                product.JOBDATE = mJobDate;
                mAdapter.notifyDataSetChanged();
            }
        }
    };

    /**
     * 保存数据
     */
    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        outState.putSerializable(PRODUCTLIST, (Serializable) mProductList);
        outState.putString(CLOTHTKTNO, mClothThtNo);
    }

}
